var express = require("express");
var router = express.Router();
const multer = require('multer');
const path = require('path'); 
const fs = require('fs');
const { User } = require('../models');
const { BASE_URL } = require("../config");

const storage = multer.diskStorage({ 
    destination: (req, file, cb) => {
        let { user_id } = req.body;
        
        User.findById(user_id).then(async res => {
            if (res === null) {
                return console.log("没有该用户");            
            } 

            let newFolderPath = path.join(__dirname, '../public/userFiles/' + res.phone + '/cover/');

            if (!fs.existsSync(newFolderPath)) {
                fs.mkdirSync(newFolderPath, { recursive: true }, err => console.error('cover 文件夹创建失败:', err));
                console.log(newFolderPath + '文件夹创建成功');
            }

            cb(null, newFolderPath);
        })
    },
    filename: (req, file, cb) => {
        const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
        cb(null, originalName);
    }
});

const upload = multer({ storage: storage });

router.post('/upload', upload.single('file'), (req, res) => {
    if (!req.file)  return res.status(400).send({ error: '请上传一个文件' });

    let { user_id } = req.body;

    User.findById(user_id)
    .then(async doc => {
        let cover_url = `/userFiles/${ doc.phone }/cover/${ Buffer.from(req.file.originalname, 'latin1').toString('utf8') }`
        doc.cover = cover_url;
        await doc.save();
        res.status(200).send({ info: '修改成功', cover: BASE_URL + cover_url });
    })
});

module.exports = router;